// 挑战模式统计API
import { NextRequest } from 'next/server';
import { query } from '@/lib/mysql';
import { getCurrentUser, ApiResponse } from '@/lib/auth';

// 获取用户挑战统计
export async function GET(request: NextRequest) {
  try {
    // 验证用户登录
    const currentUser = getCurrentUser();
    if (!currentUser) {
      return ApiResponse.unauthorized('请先登录');
    }

    // 获取用户已完成的练习总数
    const completedSql = `
      SELECT COUNT(*) as total_completed
      FROM practice_sessions
      WHERE user_id = ? AND completed = 1
    `;
    const completedResult = await query<{ total_completed: number }[]>(completedSql, [currentUser.userId]);
    const totalCompleted = completedResult[0]?.total_completed || 0;

    // 获取用户总正确题数
    const correctSql = `
      SELECT COUNT(*) as total_correct
      FROM answer_records
      WHERE user_id = ? AND is_correct = 1
    `;
    const correctResult = await query<{ total_correct: number }[]>(correctSql, [currentUser.userId]);
    const totalCorrect = correctResult[0]?.total_correct || 0;

    // 获取用户总题数
    const totalSql = `
      SELECT COUNT(*) as total_questions
      FROM answer_records
      WHERE user_id = ?
    `;
    const totalResult = await query<{ total_questions: number }[]>(totalSql, [currentUser.userId]);
    const totalQuestions = totalResult[0]?.total_questions || 0;

    // 计算排名（基于正确题数）
    const rankSql = `
      SELECT COUNT(DISTINCT user_id) + 1 as user_rank
      FROM answer_records
      WHERE is_correct = 1
      GROUP BY user_id
      HAVING COUNT(*) > ?
    `;
    const rankResult = await query<{ user_rank: number }[]>(rankSql, [totalCorrect]);
    const rank = rankResult[0]?.user_rank || 1;

    // 获取连续练习天数（简化版：统计不同日期）
    const streakSql = `
      SELECT COUNT(DISTINCT DATE(created_at)) as streak_days
      FROM practice_sessions
      WHERE user_id = ? AND completed = 1
      AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    `;
    const streakResult = await query<{ streak_days: number }[]>(streakSql, [currentUser.userId]);
    const bestStreak = streakResult[0]?.streak_days || 0;

    return ApiResponse.success({
      totalChallenges: totalQuestions,
      completedChallenges: totalCompleted,
      totalPoints: totalCorrect * 10, // 每题10分
      rank,
      bestStreak,
      accuracy: totalQuestions > 0 ? Math.round((totalCorrect / totalQuestions) * 100) : 0,
    });
  } catch (error) {
    console.error('获取挑战统计错误:', error);
    return ApiResponse.serverError('获取挑战统计失败');
  }
}

